package com.yangtu.nearbyshop.merc.web;

import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yangtu.nearbyshop.core.system.SystemConfig;
import com.yangtu.nearbyshop.core.util.DateTimeUtil;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.*;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopMercRebateService;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopOrderService;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import com.yangtu.nearbyshop.merc.annotation.LoginMerc;
import com.yangtu.nearbyshop.merc.dao.CateGoodsVo;
import com.yangtu.nearbyshop.merc.service.HomeCacheManager;
import com.yangtu.nearbyshop.merc.service.MercHomeCacheManager;
import com.yangtu.nearbyshop.merc.service.MercTokenManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页服务
 */
@RestController
@RequestMapping("/merc/home")
@Validated
public class MercHomeController {
    private final Log logger = LogFactory.getLog(MercHomeController.class);

    @Autowired
    private NearbyshopMercService mercService;

    @Autowired
    private NearbyshopOrderService orderService;

    @Autowired
    private INearbyshopOrderService mpOrderService;

    @Autowired
    private NearbyshopCategoryService categoryService;

    @Autowired
    private NearbyshopGoodsService goodsService;

    @Autowired
    private NearbyshopGoodsProductService productService;

    @Autowired
    private INearbyshopMercRebateService nearbyshopMercRebateService;


    public static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

//    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

//    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(9, 9, 1000, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);

    @GetMapping("/cache")
    public Object cache(@NotNull String key) {
        if (!key.equals("nearbyshop_cache")) {
            return ResponseUtil.fail();
        }

        // 清除缓存
        MercHomeCacheManager.clearAll();
        return ResponseUtil.ok("缓存已清除");
    }

    /**
     * 首页数据
     * @param mercId 当用户已经登录时，非空。为登录状态为null
     * @return 首页数据
     */
    @GetMapping("/index")
    public Object index(@LoginMerc Integer mercId) {
        //优先从缓存中读取
//        if (MercHomeCacheManager.hasData(MercHomeCacheManager.INDEX)) {
//            return ResponseUtil.ok(MercHomeCacheManager.getCacheData(MercHomeCacheManager.INDEX));
//        }
//        ExecutorService executorService = Executors.newFixedThreadPool(10);

        if (mercId == null) {
            return ResponseUtil.unlogin();
        }

        Map<String, Object> data = new HashMap<>();

        String mercNo =MercTokenManager.getMercNo(mercId);
        if (mercNo == null) {
            return ResponseUtil.unlogin();
        }
        NearbyshopMerc merc = mercService.queryByMercNo(mercNo);

        int orderCount = mpOrderService.count(new QueryWrapper<NearbyshopOrder2>()
                .eq("purchase_status",1)
                .eq("dispatch_status",1)
                .eq("merc_no",mercNo)
                .in("order_status", OrderUtil.STATUS_PAY,OrderUtil.STATUS_SHIP)
                .eq("deleted",0));

        data.put("dispatchOrderCount", orderCount);

        List<NearbyshopOrder2> list = mpOrderService.list(new QueryWrapper<NearbyshopOrder2>()
                .eq("dispatch_status",0)
                .eq("merc_no",mercNo)
                .eq("order_status", OrderUtil.STATUS_PAY)
                .orderByDesc("add_time"));
        BigDecimal total = new BigDecimal("0");
        for(NearbyshopOrder2 od: list){
            total = total.add(od.getActualPrice().setScale(2, BigDecimal.ROUND_UP));
        }

        //data.put("orderTodayCount", orderService.countToday(mercNo));
        data.put("todayOrderAmount",total);
        data.put("totalOrderAmount", orderService.getTotalAmt(mercNo));
        String today_start = df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        String today_end = df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MAX));

        String date = DateTimeUtil.getPastDate(1);
        String startTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";

        data.put("yesterdayRebateAmount",nearbyshopMercRebateService
                .countAllRebate(mercNo,startTime,endTime));

        data.put("totalRebateAmount",nearbyshopMercRebateService
                .countAllRebate(mercNo,null,null));

        List<NearbyshopMerc> mercList = mercService.queryByReferMercNo(mercNo);
        String selfAmt = orderService.getProfitByDt(mercNo, today_start, today_end);
        data.put("selfAmt", selfAmt);
        if (mercList.size() == 0) {
            data.put("todayAmt", selfAmt);
            data.put("referAmt", "0");
        }else {
            BigDecimal sumAmt = BigDecimal.ZERO;
            String referAmt;
            for (NearbyshopMerc referMerc: mercList) {
                referAmt = orderService.getProfitByDt(referMerc.getMercNo(), today_start, today_end);
                sumAmt = new BigDecimal(referAmt).add(sumAmt);
            }
            BigDecimal referSumAmt = sumAmt.multiply(SystemConfig.getMercReferPercent()).setScale(2, BigDecimal.ROUND_UP).stripTrailingZeros();
            data.put("todayAmt", referSumAmt.add(new BigDecimal(selfAmt)));
            data.put("referAmt", referSumAmt.stripTrailingZeros().toPlainString());
        }
        data.put("mercNm", merc.getMercName());
        data.put("mobile", merc.getMobile());
        data.put("mercNo", merc.getMercNo());

        //缓存数据
//        MercHomeCacheManager.loadData(MercHomeCacheManager.INDEX, data);
//        executorService.shutdown();
        return ResponseUtil.ok(data);
    }

    /**
     * 所有分类数据
     *
     * @return 所有分类数据
     */
    @GetMapping("all")
    public Object queryAll() {
        //优先从缓存中读取
        if (HomeCacheManager.hasData(HomeCacheManager.CATALOG)) {
            return ResponseUtil.ok(HomeCacheManager.getCacheData(HomeCacheManager.CATALOG));
        }

        // 所有一级分类目录
        List<NearbyshopCategory> l1CatList = categoryService.queryL1();

        //所有子分类列表
        Map<Integer, List<NearbyshopCategory>> allList = new HashMap<>();
        List<NearbyshopCategory> sub;
        for (NearbyshopCategory category : l1CatList) {
            sub = categoryService.queryByPid(category.getId());
            allList.put(category.getId(), sub);
        }

        // 当前一级分类目录
        NearbyshopCategory currentCategory = l1CatList.get(0);

        // 当前一级分类目录对应的二级分类目录
        List<NearbyshopCategory> currentSubCategory = null;
        if (null != currentCategory) {
            currentSubCategory = categoryService.queryByPid(currentCategory.getId());
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("categoryList", l1CatList);
        data.put("allList", allList);
        data.put("currentCategory", currentCategory);
        data.put("currentSubCategory", currentSubCategory);

        //缓存数据
        HomeCacheManager.loadData(HomeCacheManager.CATALOG, data);
        return ResponseUtil.ok(data);
    }

    /**
     * 当前分类栏目
     *
     * @param id 分类类目ID
     * @return 当前分类栏目
     */
    @GetMapping("currentGoods")
    public Object currentGoods(@NotNull Integer id) {
        // 当前分类
        NearbyshopCategory currentCategory = categoryService.findById(id);
        List<NearbyshopCategory> currentSubCategory = categoryService.queryByPid(currentCategory.getId());
        //所有子分类列表

        List<CateGoodsVo> allGoods = new ArrayList<>();
        CateGoodsVo cateGoodsVo;
        for (NearbyshopCategory category : currentSubCategory) {
            cateGoodsVo = new CateGoodsVo();
            cateGoodsVo.setCategoryId(category.getId());
            cateGoodsVo.setCategoryName(category.getName());
            List<NearbyshopGoods> goodsList = goodsService.queryByCategory(category.getId(), 0, 20);
            for(NearbyshopGoods goods : goodsList){
                goods.setPicUrl(goods.getPicUrl() +"?x-oss-process=image/resize,m_fill,h_170,w_170");
                List<NearbyshopGoodsProduct> products = productService.queryByGid(goods.getId());
                NearbyshopGoodsProduct product = products.get(0);
                if(product != null){
                    goods.setRetailPrice(product.getPrice());
                    goods.setMercProfit(product.getMercProfit());
                }
            }
            cateGoodsVo.setGoodsList(goodsList);
            allGoods.add(cateGoodsVo);
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("currentCategory", currentCategory);
        data.put("currentSubCategory", currentSubCategory);
        data.put("allGoods", allGoods);
        return ResponseUtil.ok(data);
    }

    public static void main(String[] args) {
        System.out.println(df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN)));
    }
}
